import {Component, OnInit} from '@angular/core';
import {DemarcatesService} from './demarcates.service';
import {ResponseUtil} from '../../../util/response-util';
import {MsgResult} from '../../../models/msg-result';
import {MsgConstants} from '../../../constants/constants';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {PageSubject} from '../../../util/page-subject';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Demarcate} from './demarcate';
import * as moment from 'moment';
import {SitesService} from '../sites/sites.service';
import _date = moment.unitOfTime._date;
import {MapUtil} from "../../../util/map-util";

declare var $;
declare var BMap;
@Component({
  selector: 'app-demarcates',
  templateUrl: './demarcates.component.html',
  styleUrls:['./demarcates.component.css']
})
export class DemarcatesComponent implements OnInit  {
  markerPng : string = "/assets/imgs/marker_v2_0.png";

  demarcate : Demarcate;
  demarcateForm :FormGroup;
  markerArr;
  markerId;
  map ;
  pointParam;
  pointData;
  dropSiteArr:Array<any>=[
    {"polluteName":"全部","polluteSiteType":"allSite"},
    {"polluteName":"标准站","polluteSiteType":"allPollutionSite"}
  ];
  selectedSite:any = this.dropSiteArr[0];
  isRegionMenuShow:boolean = false;
  isDropMenuShow:boolean = false;
  constructor(
    private demarcatesService : DemarcatesService,
    private sitesService : SitesService,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private  responseUtil : ResponseUtil,
    private fb: FormBuilder,
    private mapUtil : MapUtil
  ) {
    this.initObject({id:"",name:"",lat:"",lng:""});
  }

  ngOnInit() {
    this.pushPage(); //初始化面包屑导航
    this.mapUtil.loadMapScript(()=> this.initMap());
    // this.initMap(); //初始化地图
    this.administrativeDivisionTree(); //初始化行政区划树同时显示站点
    this.initSiteCategory();//初始化下拉列表选项
    this.dropDownClick(); //下拉列表点击事件
    // this.dropDownInputStyle();//下拉列表的input样式
    this.disabledEnter(); //禁用回车键
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("设备监测", "");
    this.pageSubject.pushPage("点位标定", "查询", path);
  }
  /**
   * 初始化地图
   */
  initMap () {
     $("#map").css("height",window.innerHeight-195+"px");
     this.map = new BMap.Map("map",{enableMapClick:false,minZoom:5,maxZoom:18});
     let centerPoint = new BMap.Point(113.658221,34.780377);  // 创建点坐标
     this.map.centerAndZoom(centerPoint, 12);
     //地图样式
     let mapStyle = [
      {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "off"
        }
      },
      {"featureType" : "land",
        "elementType": "geometry",
        "stylers": {
          "color": "#24252b"
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#171717",
          "weight": "0.1",
          "lightness": -6,
          "saturation": -15
        }
      },
      {
        "featureType": "highway",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      },
      {"featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#2a2b2e"
        }
      },
      {"featureType": "highway",
        "elementType": "all",
        "stylers": {
          "lightness": -42,
          "saturation": -91
        }
      },
      {"featureType": "arterial",
        "elementType": "geometry",
        "stylers": {
          "lightness": -77,
          "saturation": -94
        }
      },
      {"featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "subway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#181818"
        }
      },
      {"featureType": "railway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -52
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#313131"
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#8b8787"
        }
      },
      {"featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "lightness": -75,
          "saturation": -91
        }
      },
      {"featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -65
        }
      },
      {"featureType": "railway",
        "elementType": "all",
        "stylers": {
          "lightness": -40
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#041e3b",
          "weight": "1.0",
          "lightness": -12,
          "saturation": -15
        }
      },
      {"featureType": "water",
        "elementType": "geometry",
        "stylers": {
          "color": "#041e3b",
          "hue": "#041e3b",
          "weight": "0.1",
          "lightness": -12,
          "saturation": -15
        }
      }
    ];
     this.map.setMapStyle({styleJson:mapStyle});
     this.map.enableScrollWheelZoom();
     this.map.enableDragging();
     this.markerArr = [];
     this.markerId = [];
     this.pointData = [];
     this.pointParam = {};
  }
  /**
   *  行政区划树
   */
  administrativeDivisionTree() {
    this.demarcatesService.getRetrieveRegionsTree().subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      $("#map_area_name").val(result.data.name).data("id",result.data.id);
      this.regioCodezTree(result.data);
      // this.showMarker(); //显示但前区域的站点
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
        this.dialogService.info(result.message);
    }
  }
  /**
   *  行政区划树
   */
  private regioCodezTree(datasTree) {
    let datas = datasTree || [];
    // 新增中的树
    let userUpdateZtreeSetting = {
      callback: {
        onClick: this.regioCodeTreeClick
      }
    };
    $.fn.zTree.init($("#demarcates_site_tree"), userUpdateZtreeSetting, datas);
  }
  regioCodeTreeClick =(even, id, treeNode) => {
    $("#map_area_name").data("id",treeNode.id).val(treeNode.name).parents("label").next().hide();
  }
  /**
   *  点位标注
   */
  dragMarker(pointObj){
    let point =  new BMap.Point(pointObj.Longitude,pointObj.Latitude);
    let newIcon = new BMap.Icon(this.markerPng, new BMap.Size(101,39));
    let label = new BMap.Label("<div class='one-site-label-name'>"+pointObj.siteName+"</div><span style='display:block;white-space:normal;width: 100px;padding-top: 2px;: ;'>"+pointObj.siteName+"</span>");
    let marker = new BMap.Marker(point,{icon:newIcon});// 创建标注
    label.setStyle({                                   //给label设置样式，任意的CSS都是可以的
      border:"0",
      background:"transparent",
      textAlign:"center",
      color:"#fff"
    });
    marker.setTitle(pointObj.siteName);
    marker.setLabel(label);
    this.map.addOverlay(marker);  // 将标注添加到地图中
    this.map.addOverlay(label);
    let id = pointObj.siteCode;
    let name = pointObj.siteName;
    this.markerId.push(id);
    this.markerArr.push(marker);
    this.pointData.push(pointObj);
    marker.enableDragging();
    marker.addEventListener("dragend",function(){   //标注的拖拽事件
      this.markerDragFunction(marker,id,name);
    }.bind(this));
    marker.addEventListener("click",function(){  //标注的点击事件
      this.markerClickFunction(marker,pointObj);
    }.bind(this));
  }
  /**
   * 实例化对象
   */
  private initObject(obj) {
    // this.demarcate = new Demarcate("岗李水库","34.83349","113.653622");
    this.demarcate = new Demarcate(obj.id,obj.name,obj.lng,obj.lat);
    this.buildForm();
  }
  /**
   * 构造表单
   */
  buildForm():void{
    this.demarcateForm = this.fb.group({
      "demarcateId" : [this.demarcate.demarcateId],
      "demarcateName" : [this.demarcate.demarcateName],
      "demarcateLng"  : [this.demarcate.demarcateLng,[
        Validators.required,
        Validators.pattern(/([1-9]\d*.\d*|0.\d*[1-9]\d*)/)
      ]],
      "demarcateLat"  : [this.demarcate.demarcateLat,[
        Validators.required,
        Validators.pattern(/([1-9]\d*.\d*|0.\d*[1-9]\d*)/)
      ]]
    })
    this.demarcateForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.demarcateForm) {
      return;
    }
    const form = this.demarcateForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }
  /**
   * 校验字段
   * @type {{demarcateLng: num; demarcateLat: num}}
   */
  formErrors = {
    'demarcateLng': '',
    'demarcateLat': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'demarcateLng': {
      'required': '经度不能为空',
      'pattern': '格式不正确'
    },
    'demarcateLat': {
      'required': '纬度不能为空',
      'pattern': '格式不正确'
    }
  };
  //form关闭事件
  close(){
    $("#one-dialog-form").hide();
    this.enableDrag();
  }
  /**
   * form取消事件
   */
  cancel(){
    let pointIndex = this.markerId.indexOf($("#map_point_id").val());
    let pointDetail = this.pointData[pointIndex];
    let clickMarker = this.markerArr[pointIndex];
    let point = new BMap.Point(pointDetail.Longitude,pointDetail.Latitude);
    this.map.centerAndZoom(point,this.map.getZoom());
    clickMarker.setPosition(point);
    this.enableDrag();
    $("#one-dialog-form").hide();
  }
  /**
   * form提交事件
   */
  onSubmit(){
    this.enableDrag();
    this.demarcate = this.demarcateForm.value;
    let index = this.markerId.indexOf($("#map_point_id").val());
    let clickMarker = this.markerArr[index];
    this.pointData[index].Longitude = this.demarcate.demarcateLng;
    this.pointData[index].Latitude = this.demarcate.demarcateLat;
    let point = new BMap.Point(this.demarcate.demarcateLng,this.demarcate.demarcateLat);
    this.map.centerAndZoom(point,this.map.getZoom());
    clickMarker.setPosition(point);
    $("#one-dialog-form").hide();
    this.demarcatesService.postPoint(this.demarcate).subscribe(
      result => this.responseUtil.success(result, this.postPointInfo),
      message => this.responseUtil.error(message)
    )
  }
  /**
   * form提交事件
   */
  postPointInfo = (result: MsgResult) => {
    console.log(result);
    this.dialogService.info(result.message);
  };
  /**
   * 标注拖拽函数
   */
  markerDragFunction (marker,id,name){
    let markerPoint = marker.getPosition();
    this.initObject({id:id,name:name,lat:markerPoint.lat,lng:markerPoint.lng});
    this.disableDrag(id);
    $("#one-dialog-form").show();
  }
  /**
   * 标注点击函数
   */
  markerClickFunction (marker,pointObj){
    if($("#one-dialog-form").css("display") == "block"){
      return false;
    }else{
      console.log(pointObj);
      this.initObject({id:pointObj.siteCode,name:pointObj.siteName,lat:pointObj.Latitude,lng:pointObj.Longitude});
      let point = new BMap.Point(pointObj.Longitude,pointObj.Latitude);
      this.map.centerAndZoom(point,this.map.getZoom());
      this.disableDrag(pointObj.siteCode);
      $("#one-dialog-form").show();
    }
  }
  /**
   * 禁止推拽
   */
  disableDrag (id){
    let index = this.markerId.indexOf(id);
    this.markerArr.forEach((marker, i) => {
      if(i != index){
        marker.disableDragging();
        marker.getLabel().setStyle({"color":"#fff"})
      }else{
        marker.enableDragging();
        marker.getLabel().setStyle({"color":"#F12F1C"})
      }
    });
  }
  /**
   * 允许推拽
   */
  enableDrag(){
    this.markerArr.forEach((marker) => {
      marker.enableDragging();
      marker.getLabel().setStyle({"color":"#fff"})
    });
  }
  /**
   * 根据条件选择站点
   */
  showMarker(){
    this.clearMarker();
    this.pointParam.regionCode = $("#map_area_name").data("id");
    this.pointParam.siteType = this.selectedSite.polluteSiteType;
    this.pointParam.siteName = $(".one-map-search input").val();
    let siteCategory = $("#map_site_category").data("type");
    this.pointParam.siteCategory = "";
    this.demarcatesService.getPoint(this.pointParam).subscribe(
      result => this.responseUtil.success(result,this.batchAddMarker),
      message => this.responseUtil.error(message)
    )
  }
  /**
   * 显示站点
   */
  private batchAddMarker =(result : MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.showPointInfo(result.data);
      result.data.forEach((pointObj,i) => {
        i == 0 && this.map.centerAndZoom(new BMap.Point(pointObj.Longitude,pointObj.Latitude),this.map.getZoom());
        this.dragMarker(pointObj);
      });
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  /**
   * 显示列表
   */
  showPointInfo(data){
    let pointHtml = "";
    let clickNum = 1;
    $(".one-map-point-list-body").html("");
    this.siteNameClick();
    this.loadData(clickNum,data);
    console.log(data.length);
    if(data.length>10){
      $(".one-map-point-list-footer li").click(function(){
        clickNum++;
        this.loadData(clickNum,data);
      }.bind(this));
    }else{
      $(".one-map-point-list-footer li").html("暂无数据");
    }
  }
  /**
   * 加载数据
   */
  loadData(clickNum,data){
    let clickData = data.slice((clickNum-1)*10,10*clickNum);
    let pointHtml = "";
    clickData.forEach((pointObj,i) => {
      pointHtml += "<li data-code='"+pointObj.siteCode+"'>"+pointObj.siteName+"</li>";
    });
    clickNum>=Math.ceil(data.length/10) && $(".one-map-point-list-footer li").html("暂无数据");
    $(".one-map-point-list-body").append(pointHtml);
  }
  /**
   * 列表上的点击事件
   */
  siteNameClick(){
    $(".one-map-point-list-body").on("click","li",function(e){
      let siteIndex = this.markerId.indexOf(String($(e.target).data("code")));
      let pointObj = this.pointData[siteIndex];
      if($("#one-dialog-form").css("display") == "block"){
        return false;
      }else{
        this.initObject({id:pointObj.siteCode,name:pointObj.siteName,lat:pointObj.Latitude,lng:pointObj.Longitude});
        this.disableDrag(pointObj.siteCode);
        $("#one-dialog-form").show();
      }
    }.bind(this))
  }
  /**
   * 清除地图上的标注和删除存储的数据
   */
  clearMarker(){
    this.map.clearOverlays();
    this.markerId=[];
    this.markerArr=[];
    this.pointData=[];
  }
  /**
   * 点击展开或隐藏下拉列表
   */
  dropDownClick(){
    $(".one-map-point-header").on("click","input",function(){
      $(this).parent().next().show().parent().siblings().children(".dropdown-menu").hide();
    }).on("mouseleave",".one-map-point-dropdown",function(){
      $(this).children(".dropdown-menu").hide();
    });
    $(".one-map-point-dropdown").on("ifClicked","input",function(){
      let chooseType = $(this).parents("label").text();
      let type = $(this).data("type");
      $(this).parents(".dropdown-menu").hide().prev().find("input").val(chooseType).data("type",type);
    });
    $(".one-left-dropdown").on("ifClicked","input",function(){
      let type = $(this).data("type");
      if(type == "all"){
        $("#demarcates_type .all").iCheck('check');
        $("#map_site_type").val("全部").data("type","allSite")
      }else{
        let firstChooseElem = $("#demarcates_type ."+type)[0];
        $(firstChooseElem).iCheck('check');
        $("#map_site_type").val($(firstChooseElem).parents("label").text()).data("type",$(this).data("type"))
      }
      $(".one-right-dropdown input").each(function(){
        if(type == "all"){
          $(this).parents("li").show();
        }else{
          $(this).hasClass(type)? $(this).parents("li").show(): $(this).parents("li").hide();
        }
      });
    })
  }
  /**
   * 下拉列表中的input样式
   */
  // dropDownInputStyle(){
  //   $(".dropdown-menu input").iCheck({
  //     checkboxClass: 'icheckbox_minimal-green',
  //     radioClass: 'iradio_minimal-green',
  //     increaseArea: '20%' // optional
  //   })
  // }
 /*
 * 禁用回车键
 */
 disabledEnter(){
   document.onkeydown =function(e){
     if(e.keyCode ==13){
       return;
     }
   }
 }

  /**
   * 初始化站点类型
   */
  initSiteCategory(){
    this.sitesService.getSiteCategoryInfos().subscribe(
      result =>this.responseUtil.success(result ,this.processSiteCategoryResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteCategoryResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getDropSiteData (result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
private getDropSiteData(data){
  data.forEach((currentValue,index)=>{
      switch(currentValue.siteTypeCode)
      {
        case "012":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"VOCsSite"})
          break;
        case "301":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"soilPollutionSite"})
          break;
        case "203":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"PHWaterQualityMonitorSite"})
          break;
        case "001":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"nationalSite"})
          break;
        case "102":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"raiseDustSite"})
          break;
        case "103":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"lampblackSite"})
          break;
        case "104":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"sprayBoothSite"})
          break;
        case "201":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"waterPollutionSite"})
          break;
        // case "005":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "006":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "007":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "008":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "009":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "010":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        // case "011":
        //   this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":""})
        //   break;
        case "004":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"smallAirSite"})
          break;
        case "003":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"citySite"})
          break;
        case "002":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"provinceSite"})
          break;
        case "101":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"industrySite"})
          break;
        case "105":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"gasStationSite"})
          break;
        case "108":
          this.dropSiteArr.push({"polluteName":currentValue.remark,"polluteSiteType":"skyEyeSite"})
          break;
        default:
      }
  })

}

clickSite(list){
  this.selectedSite = list;
}
  getDropMenuShow(){
  this.isDropMenuShow = true;
  }
  getDropMenuHide(){
    this.isDropMenuShow = false;
  }
  getRegionMenuShow(){
    this.isDropMenuShow = true;
  }
  getRegionMenuHide(){
    this.isDropMenuShow = false;
  }
}












